package com.fyx.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fyx.config.*;
import com.fyx.entity.*;
import com.fyx.mapper.MeituanReCountMapper;
import com.fyx.mapper.ShareMapper;
import com.fyx.mapper.SysDictDetailMapper;
import com.fyx.service.IActiveDataService;
import com.fyx.until.DateUtil;
import com.fyx.until.HttpUtil;
import com.fyx.until.JsonUtil;
import com.fyx.until.OSSUtil;
import com.fyx.utils.RedisUtils;
import com.fyx.utils.SecurityUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ddf.NullEscherSerializationListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.*;

@Service
public class ActiveDataServiceImpl  extends ServiceImpl<SysDictDetailMapper, SysDictDetail> implements IActiveDataService {

    @Autowired
    @Resource(name = PrimaryMongoConfig.MONGO_TEMPLATE)
    private MongoTemplate mongoTemplate;

    @Resource(name = SecondaryMongoConfig.MONGO_TEMPLATE)
    private MongoTemplate secondaryMongoTemplate;

    @Resource(name = TertiaryMongoConfig.MONGO_TEMPLATE)
    private MongoTemplate tertiaryMongoTemplate;

    @Resource(name = SeventhMongoConfig.MONGO_TEMPLATE)
    private MongoTemplate seventhMongoTemplate;

    @Resource(name = FiveMongoConfig.MONGO_TEMPLATE)
    private MongoTemplate fiveMongoTemplate;

    @Autowired
    private MeituanReCountMapper meituanReCountMapper;

    @Override
    public Map getMeituReList(MeituanReCount meituanReCount, Pageable pageable){
        Page<MeituanReCount> page = new Page<>(pageable.getPageNumber()+1,pageable.getPageSize());
        QueryWrapper<MeituanReCount> wrapper =new QueryWrapper<>();
        if(meituanReCount.getQTime()!=null){
            wrapper.ge("time",meituanReCount.getQTime().get(0).getTime()/1000);
            wrapper.le("time",meituanReCount.getQTime().get(1).getTime()/1000);
        }
        wrapper.orderByDesc("time");
        IPage<MeituanReCount> ipage = meituanReCountMapper.selectPage(page,wrapper);
        List<MeituanReCount> list = ipage.getRecords();
        String[] xData=new String[list.size()];
        Map yDataMaps = new HashMap();
        if(list.size()>0) {
            for (int i = 0; i < list.size(); i++) {
                xData[i] = DateUtil.timeStamp2Date(list.get(i).getTime() + "", "yyyy-MM-dd ").trim();
                String sad[]= list.get(i).getPerson().split("#");
                Integer ewq[]=new Integer[26];
                for (int j=0;j<sad.length;j++){
                    ewq[j]=Integer.parseInt(sad[j].split("@")[1]);
                }
                yDataMaps.put( (i+1)+"",ewq);
            }
        }
        Query query=new Query();
        query.skip((pageable.getPageNumber())*pageable.getPageSize());
        query.limit(pageable.getPageSize());
        Criteria criteria = new Criteria();
        criteria.and("remark").exists(true);
        if(meituanReCount.getQTime()!=null){
            criteria.and("unix_time").gte(meituanReCount.getQTime().get(0).getTime()/1000).lt(meituanReCount.getQTime().get(1).getTime()/1000);
        }
        if(meituanReCount.getId()!=null){
            criteria.and("pid").is(meituanReCount.getId()+"");
        }
        query.addCriteria(criteria);
        query.with( Sort.by(Sort.Direction.DESC,new String[]{"unix_time"}));
        List<WithdrawEntity> list1=secondaryMongoTemplate.find(query,WithdrawEntity.class);
        if(list1.size()>0){
            for(WithdrawEntity withdrawEntity:list1){
               criteria=new Criteria();
               criteria.and("userid").is(withdrawEntity.getPid());
               UserEntity userEntity=mongoTemplate.findOne(new Query().addCriteria(criteria),UserEntity.class);
               if(userEntity!=null){
                   withdrawEntity.setUsername(userEntity.getNickname());
                   withdrawEntity.setRegTime((int)userEntity.getReg_time());
                   withdrawEntity.setTotalFee(userEntity.getAll_fee());
                   withdrawEntity.setGames((int)userEntity.getPlayinfo().get("total"));
               }
            }
        }
        long total=secondaryMongoTemplate.count(query, WithdrawEntity.class,"withdraw");
        Map map=new HashMap();
        map.put("chartData",yDataMaps);
        map.put("xData",xData);
        map.put("content",list1);
        map.put("totalElements",total);
        map.put("countData",1);
        return map;
    }

    @Override
    public Map gameEmail(GameEmailEntity gameEmailEntity, Pageable pageable) {
        Query query=new Query();
        query.skip((pageable.getPageNumber())*pageable.getPageSize());
        query.limit(pageable.getPageSize());
        Criteria criteria = new Criteria();

        if(StringUtils.isNotBlank(gameEmailEntity.getReceiver())){
            criteria.and("receiver").is(gameEmailEntity.getReceiver());
        }

        if (gameEmailEntity.getMail_type()!=0){
            criteria.and("mail_type").is(gameEmailEntity.getMail_type());
        }

        if (gameEmailEntity.getMail_stype()!=0){
            criteria.and("mail_stype").is(gameEmailEntity.getMail_stype());
        }

        if (gameEmailEntity.getQTime()!=null){
            criteria.andOperator(Criteria.where("create_time").gte(gameEmailEntity.getQTime().get(0).getTime()/1000).lte(gameEmailEntity.getQTime().get(1).getTime()/1000));
        }

        query.addCriteria(criteria);
        query.with( Sort.by(Sort.Direction.DESC,new String[]{"create_time"}));
        List<GameEmailEntity> list;long total;
        if(gameEmailEntity.getFlag()!=null&&gameEmailEntity.getFlag().equals("clmj")) {
            list = fiveMongoTemplate.find(query, GameEmailEntity.class);
            total = fiveMongoTemplate.count(query, GameEmailEntity.class, "mail");
        }else {
           list = mongoTemplate.find(query, GameEmailEntity.class);
            total = mongoTemplate.count(query, GameEmailEntity.class, "mail");
        }
        for (GameEmailEntity gameGameEmailEntity1:list){
            if (StringUtils.isNotBlank(gameGameEmailEntity1.getReceiver())){
                UserEntity userEntity;
                if(gameEmailEntity.getFlag()!=null&&gameEmailEntity.getFlag().equals("clmj")) {
                    userEntity = fiveMongoTemplate.findOne(new Query(Criteria.where("userid").is(gameGameEmailEntity1.getReceiver())), UserEntity.class);
                    gameEmailEntity.setFlag("clmj");
                }else {
                    userEntity = mongoTemplate.findOne(new Query(Criteria.where("userid").is(gameGameEmailEntity1.getReceiver())), UserEntity.class);
                    gameEmailEntity.setFlag("hzmj");
                }
                if (userEntity!=null){
                    gameGameEmailEntity1.setNickname(userEntity.getNickname());
                }
            }
        }

        Map map=new HashMap();
        map.put("list",list);
        map.put("total",total);
        return map;
    }

    @Override
    public boolean delMail(String  id,String flag) throws IOException{
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("mail_id",id);
        jsonObject.put("username",SecurityUtils.getCurrentUsername());
        JSONObject map = new JSONObject();
        map.put("cmd","delete_mail");
        map.put("args",jsonObject);
        try {
            String result="";
            if(flag.equals("clmj")){
                result =HttpUtil.post(RequestConfig.baseRequestUrl2, map.toJSONString(),"utf-8");
            }else {
                result =HttpUtil.post(RequestConfig.baseRequestUrl, map.toJSONString(),"utf-8");
            }
            JSONObject js= JSONObject.parseObject(result);
            if(js.getString("result").equals("true")){
                return true;
            }else {
                return false;
            }
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public Map telephoneCharge(TelephoneChargeEntity telephoneChargeEntity, Pageable pageable) {
        Query query=new Query();
        query.skip((pageable.getPageNumber())*pageable.getPageSize());
        query.limit(pageable.getPageSize());
        Criteria criteria = new Criteria();
        if(telephoneChargeEntity.getReceiver()!=null){
            criteria.and("receiver").is(telephoneChargeEntity.getReceiver());
        }
        query.addCriteria(criteria);
        query.with(Sort.by(Sort.Direction.DESC,new String[]{"id"}));
        List<TelephoneChargeEntity> list=mongoTemplate.find(query,TelephoneChargeEntity.class);
        long total=mongoTemplate.count(query, TelephoneChargeEntity.class);

        Map map=new HashMap();
        map.put("list",list);
        map.put("total",total);
        return map;
    }

    @Override
    public void sendhf(WithdrawEntity withdrawEntity) {
        System.out.println(withdrawEntity);
        if(withdrawEntity.getFlag()==true) {
            Update update = new Update();
            update.set("update_name", SecurityUtils.getCurrentUsername());
            update.set("update_time", new Date().getTime() / 1000);
            update.set("flag", true);
            secondaryMongoTemplate.updateFirst(new Query(Criteria.where("_id").is(withdrawEntity.getId())), update, WithdrawEntity.class);
            Thread t = new Thread(new Runnable() {
                public void run() {
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("p_id", withdrawEntity.getPid());
                    jsonObject.put("title", "话费充值成功");
                    jsonObject.put("content", "尊敬的玩家:\n您在红包活动中领取的话费已充值到指定手机号，预计10分钟到账，请注意查收");
                    jsonObject.put("mail_type", 1);
                    jsonObject.put("award", null);
                    jsonObject.put("end_time", (new Date().getTime() / 1000) + 168 * 3600);
                    JSONObject map = new JSONObject();
                    map.put("cmd", "send_mail");
                    map.put("args", jsonObject);
                    try {
                        HttpUtil.post(RequestConfig.baseRequestUrl, map.toJSONString(), "utf-8");
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            });
            t.start();
        }
    }


    @Override
    public Map getActiveList(ActivityListEntity activityListEntity, Pageable pageable){
        Query query = new Query();
        query.skip((pageable.getPageNumber())*pageable.getPageSize());
        query.limit(pageable.getPageSize());
        Criteria criteria = new Criteria();
        if (activityListEntity.getData_id()!=0){
            criteria.and("data_id").is(activityListEntity.getData_id());
        }
        if(activityListEntity.getActive_type()!=0){
            criteria.and("active_type").is(activityListEntity.getActive_type());
        }
        if (activityListEntity.getQTime()!=null){
            criteria.and("begintime").gte(activityListEntity.getQTime().get(0).getTime()/1000);
            criteria.and("endtime").lte(activityListEntity.getQTime().get(1).getTime()/1000);
        }
        query.addCriteria(criteria);
        query.with( Sort.by(Sort.Direction.DESC,new String[]{"endtime"}));
        List<ActivityListEntity> list;long total=0l;
        if(activityListEntity.getFlag()!=null&&activityListEntity.getFlag().equals("totalcl")) {
            list = seventhMongoTemplate.find(query, ActivityListEntity.class);
             total = seventhMongoTemplate.count(query, ActivityListEntity.class);
        }else {
            list = tertiaryMongoTemplate.find(query, ActivityListEntity.class);
            total = tertiaryMongoTemplate.count(query, ActivityListEntity.class);
        }
        Map map =new HashMap();
        map.put("list",list);
        map.put("total",total);
        return map;
    }

    @Override
    public boolean addActive(ActivityListEntity activityListEntity){
        try {
            Query query= new Query();
            query.with(Sort.by(Sort.Direction.DESC,new String[]{"id"}));
            ActivityListEntity activityListEntity1=tertiaryMongoTemplate.findOne(query,ActivityListEntity.class);
            activityListEntity.setBegintime(Long.valueOf( activityListEntity.getQTime().get(0).getTime()/1000).intValue());
            activityListEntity.setEndtime(Long.valueOf( activityListEntity.getQTime().get(1).getTime()/1000).intValue());

            if(activityListEntity1!=null){
                activityListEntity.setAct_id(activityListEntity1.getAct_id()+1);}
            else{
                activityListEntity.setAct_id(1);
            }
            activityListEntity.setData_id(1);
            activityListEntity.setCreate_time(Long.valueOf( new Date().getTime()/1000).intValue());
            activityListEntity.setCreate_user(SecurityUtils.getCurrentUsername());
            if(activityListEntity.getFlag()!=null&&activityListEntity.getFlag().equals("totalcl")) {
                seventhMongoTemplate.insert(activityListEntity);
            }else {
                tertiaryMongoTemplate.insert(activityListEntity);
            }
            return true;
        }catch (Exception e){
            return false;
        }

    }

    @Override
    public boolean delActive(String  id,String flag){
        try {
            Update update=new Update();
            update.set("enable",0);
                seventhMongoTemplate.updateFirst(new Query(Criteria.where("_id").is(id)), update, ActivityListEntity.class);
                tertiaryMongoTemplate.updateFirst(new Query(Criteria.where("_id").is(id)), update, ActivityListEntity.class);
            return true;
        }catch (Exception e){
            return false;
        }
    }

    @Override
    public Map getShare(Pageable pageable) {
        Map map=new HashMap();
        QueryWrapper<ShareEntity> wrapper=new QueryWrapper<>();
        List<ShareEntity> list=  shareMapper.selectList(wrapper);
        map.put("list",list);
        map.put("total",list.size());
        System.out.println(list);
        return map;
    }
    @Autowired
    private RedisUtils redisUtils;

    @Override
    public Map getShare1(String type) {
        Map map=new HashMap();
        if(type==null){
           if(redisUtils.hasKey("getShare")){
                map=(Map) redisUtils.get("getShare");
          }
            else {
            QueryWrapper<ShareEntity> wrapper=new QueryWrapper<>();
            wrapper.eq("type","share");
            List<ShareEntity> list=  shareMapper.selectList(wrapper);
            for(ShareEntity shareEntity:list){
                shareEntity.setCreateUser(null);
                shareEntity.setCreateTime(null);
            }
            map.put("list",list);
            map.put("total",list.size());
           redisUtils.set("getShare",map,86400);
          }
        }else {
            if(redisUtils.hasKey(type)){
                map=(Map) redisUtils.get(type);
            }
            else {
                QueryWrapper<ShareEntity> wrapper=new QueryWrapper<>();
                wrapper.eq("type",type);
                List<ShareEntity> list=  shareMapper.selectList(wrapper);
                for(ShareEntity shareEntity:list){
                    shareEntity.setCreateUser(null);
                    shareEntity.setCreateTime(null);
                }
                map.put("list",list);
                map.put("total",list.size());
                redisUtils.set(type,map,86400);
            }
        }
        return map;
    }

    @Autowired
    ShareMapper shareMapper;

    @Autowired
    OSSUtil ossUtil;

    @Override
    public String doShare(MultipartFile file) {
        String fileName = null;
        try {
            fileName= ossUtil.upload(file);
            return fileName;
        } catch (IOException e) {
            e.printStackTrace();
            return e.getMessage();
        }

    }

    @Override
    public boolean addShare(ShareEntity shareEntity){
      try {
          shareEntity.setCreateTime(new Date().getTime()/1000);
          shareEntity.setCreateUser(SecurityUtils.getCurrentUsername());
          shareMapper.insert(shareEntity);
          return true;
      }catch (Exception e){
          return false;
      }

    }

    @Override
    public  boolean editShare(ShareEntity shareEntity){
        try {
            shareEntity.setCreateTime(new Date().getTime()/1000);
            shareEntity.setCreateUser(SecurityUtils.getCurrentUsername());
            shareMapper.updateById(shareEntity);
            return true;
        }catch (Exception e){
            return false;
        }
    }

    @Override
    public boolean delShare(int  id){
      try{  QueryWrapper<ShareEntity> wrapper=new QueryWrapper<>();
        wrapper.eq("id", id);
        shareMapper.delete(wrapper);
        return true;}
      catch (Exception e){
          return false;
      }
    }

    @Override
    public boolean toActiveNotice(String  id) throws IOException{
        JSONObject jsonObject = new JSONObject();
        JSONObject map = new JSONObject();
        map.put("cmd","toNotice_active");
        map.put("args",jsonObject);
        try {
            String result =HttpUtil.post(RequestConfig.baseRequestUrl, map.toJSONString(),"utf-8");
            JSONObject js= JSONObject.parseObject(result);
            if(js.getString("result").equals("true")){
                return true;
            }else {
                return false;
            }
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }


    @Override
    public boolean editActive(ActivityListEntity activityListEntity){
        try {
            Update update=new Update();
          //  update.set("id",activityListEntity.getAct_id());
            update.set("location",activityListEntity.getLocation());
            update.set("subtype",activityListEntity.getSubtype());
            update.set("name",activityListEntity.getName());
            update.set("level",activityListEntity.getLevel());
            update.set("enable",activityListEntity.getEnable());
            update.set("active_type",activityListEntity.getActive_type());
            update.set("configstr",activityListEntity.getConfigstr());
            update.set("create_time",Long.valueOf( new Date().getTime()/1000).intValue());
            if(activityListEntity.getQTime()!= null) {
                update.set("begintime", Long.valueOf(activityListEntity.getQTime().get(0).getTime() / 1000).intValue());
                update.set("endtime", Long.valueOf(activityListEntity.getQTime().get(1).getTime() / 1000).intValue());
            }
            if(activityListEntity.getFlag()!=null&&activityListEntity.getFlag().equals("totalcl")) {
                seventhMongoTemplate.updateFirst(new Query(Criteria.where("_id").is(activityListEntity.getId())), update, ActivityListEntity.class);
            }
            else {
                tertiaryMongoTemplate.updateFirst(new Query(Criteria.where("_id").is(activityListEntity.getId())), update, ActivityListEntity.class);
            }
            return true;
        }catch (Exception e){
            return false;
        }

    }

}
